package com.briup.smartcity_group6.service.Impl;


import com.briup.smartcity_group6.bean.basic.Comment;
import com.briup.smartcity_group6.dao.basic.CommentMapper;
import com.briup.smartcity_group6.dao.ext.CommentExtMapper;
import com.briup.smartcity_group6.exception.ServiceException;
import com.briup.smartcity_group6.service.ICommentService;
import com.briup.smartcity_group6.utils.ResultCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper mapper;
    @Autowired
    private CommentExtMapper extMapper;
    public void checkComment(int id, int status) {
        Comment comment = mapper.selectByPrimaryKey(id);
        if (comment == null){
            throw new ServiceException(ResultCode.COMMENT_NOT_FOUND);
        }
        extMapper.changeStatusById(id,status);
        mapper.updateByPrimaryKeySelective(comment);
    }

    public PageInfo<Comment> pageQuery(int pageNum, int pageSize, String keywords) {
        PageInfo<Comment> pageInfo = PageHelper.startPage(pageNum, pageSize, keywords).doSelectPageInfo(
                ()-> extMapper.selectAll()
        );
        if(keywords == null){
            throw new ServiceException(ResultCode.KEY_NOT_FOUND);
        }
        return pageInfo;
    }

    public void deleteById(int id) {
        Comment comment = mapper.selectByPrimaryKey(id);
        if (comment == null){
            throw new ServiceException(ResultCode.Comment_Disappear);
        }
        List<Integer> parentId = extMapper.findIdByParentId(id);
        for (int i = 0; i < parentId.size(); i++){
            mapper.deleteByPrimaryKey(parentId.get(i));
        }
        mapper.deleteByPrimaryKey(id);
    }

    public void batchDelete(int[] ids) {
        for (int i = 0; i < ids.length; i++){
            Comment comment = mapper.selectByPrimaryKey(ids[i]);
            if(comment == null){
                throw new ServiceException(ResultCode.COMMENT_NOT_FOUND);
            }
        }
        for (int i = 0; i < ids.length; i++){
            List<Integer> parentId = extMapper.findIdByParentId(ids[i]);
            for (int k: parentId){
                mapper.deleteByPrimaryKey(k);
            }
        }
    }
}
